package com.mcyy.financemanager.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcyy.financemanager.entity.TbFinanceInfo;
import com.mcyy.financemanager.entity.Vo.Financequeryvo;
import com.mcyy.financemanager.entity.Vo.LishiVo;
import com.mcyy.financemanager.mapper.TbFinanceInfoMapper;
import com.mcyy.financemanager.service.TbFinanceInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@Api("收支")
@RequestMapping("/financeManager")
public class FinanceInfoController {
    @Autowired
    private TbFinanceInfoService tbFinanceInfoService;
    @Autowired
    private TbFinanceInfoMapper tbFinanceInfoMapper;
    /**
     * 新增收支
     * 支出 -
     * 收入 +
     */
    @PostMapping("addfinanceinfo")
    @ApiOperation("新增收支")
    public List<TbFinanceInfo> addfinanceinfo(@RequestBody TbFinanceInfo tbFinanceInfo){
        int id=(int)(Math.random()*1000000000);
        tbFinanceInfo.setId(id);
        //报销人 claimerUserId a 默认
        //事由 reason a
        //收入支出时间 updateTime a
        //收支金额 sum a
        //报销类型 type a
        //报销日期 reasonTime a

        //余额 balance 计算  基于reasonTime 做加减法
        //记录人id 当前登录用户 recorderUserId a

        /**
         * 根据输入的报销日期 reasonTime 定位到排序位置
         * 基于前面最后时间的余额  计算当前日期的余额
         * 后面的余额自动加减（需要遍历）
         */
        //1获取reasonTime前一个或者相同时间的balance
        QueryWrapper<TbFinanceInfo> xiaodeng=new QueryWrapper<>();
        xiaodeng.le("reason_time",tbFinanceInfo.getReasonTime());
        xiaodeng.last("order by reason_time desc");

        List<TbFinanceInfo> tbFinanceInfoList=tbFinanceInfoService.list(xiaodeng);
        //得到前面最后一个reason_time  取出最进的balance
        if(tbFinanceInfoList.size()!=0){
            Date lastreason_time=tbFinanceInfoList.get(0).getReasonTime();

            //取出最进的balance
            QueryWrapper<TbFinanceInfo> zuijin=new QueryWrapper<>();
            zuijin.eq("reason_time",lastreason_time);
            zuijin.last("order by update_time desc");
            List<TbFinanceInfo> zuijinlist=tbFinanceInfoService.list(zuijin);
            //取出最后一个balance
            String lastbalance=null;
            lastbalance=zuijinlist.get(0).getBalance();

            //插入当前新增的数据
            double newbalance =Double.parseDouble(lastbalance);
            if(tbFinanceInfo.getType()==1){//支出
                newbalance=newbalance-Double.parseDouble(tbFinanceInfo.getSum());
            }else {
                newbalance=newbalance+Double.parseDouble(tbFinanceInfo.getSum());
            }
            tbFinanceInfo.setBalance(newbalance+"");
        }else {
            if(tbFinanceInfo.getType()==1){
                tbFinanceInfo.setBalance("-"+tbFinanceInfo.getSum());
            }else {
                tbFinanceInfo.setBalance(tbFinanceInfo.getSum());
            }
        }


        boolean a=tbFinanceInfoService.save(tbFinanceInfo);


        //到这里   前面的部分完成了

        //处理后面的数据  reason_time升序
        List<TbFinanceInfo> dayulist=tbFinanceInfoMapper.getdayu(tbFinanceInfo.getReasonTime());
        //遍历dayulist 如果有相同reason_time 就基于update_time 升序asc
        if(dayulist.size()>0){
            double tempbalance=Double.parseDouble(tbFinanceInfo.getBalance());
            for(int i=0;i<dayulist.size();i++){
                TbFinanceInfo dadet=new TbFinanceInfo();
                dadet.setId(dayulist.get(i).getId());
                if(dayulist.get(i).getType()==1){
                    tempbalance=tempbalance-Double.parseDouble(dayulist.get(i).getSum());
                }else {
                    tempbalance=tempbalance+Double.parseDouble(dayulist.get(i).getSum());
                }
                dadet.setBalance(tempbalance+"");
                tbFinanceInfoService.updateById(dadet);
            }
        }
        return dayulist;
    }

    @PostMapping("updatafinanceinfo")
    @ApiOperation("修改收支")
    public boolean updatafinanceinfo(@RequestBody TbFinanceInfo tbFinanceInfo){
       deletefinanceinfo(tbFinanceInfo.getId());
        //1获取reasonTime前一个或者相同时间的balance
        QueryWrapper<TbFinanceInfo> xiaodeng=new QueryWrapper<>();
        xiaodeng.le("reason_time",tbFinanceInfo.getReasonTime());
        xiaodeng.last("order by reason_time desc");

        List<TbFinanceInfo> tbFinanceInfoList=tbFinanceInfoService.list(xiaodeng);
        //得到前面最后一个reason_time  取出最进的balance
        if(tbFinanceInfoList.size()!=0){
            Date lastreason_time=tbFinanceInfoList.get(0).getReasonTime();

            //取出最进的balance
            QueryWrapper<TbFinanceInfo> zuijin=new QueryWrapper<>();
            zuijin.eq("reason_time",lastreason_time);
            zuijin.last("order by update_time desc");
            List<TbFinanceInfo> zuijinlist=tbFinanceInfoService.list(zuijin);
            //取出最后一个balance
            String lastbalance=null;
            lastbalance=zuijinlist.get(0).getBalance();

            //插入当前新增的数据
            double newbalance =Double.parseDouble(lastbalance);
            if(tbFinanceInfo.getType()==1){//支出
                newbalance=newbalance-Double.parseDouble(tbFinanceInfo.getSum());
            }else {
                newbalance=newbalance+Double.parseDouble(tbFinanceInfo.getSum());
            }
            tbFinanceInfo.setBalance(newbalance+"");
        }else {
            if(tbFinanceInfo.getType()==1){
                tbFinanceInfo.setBalance("-"+tbFinanceInfo.getSum());
            }else {
                tbFinanceInfo.setBalance(tbFinanceInfo.getSum());
            }
        }


        boolean a=tbFinanceInfoService.save(tbFinanceInfo);


        //到这里   前面的部分完成了

        //处理后面的数据  reason_time升序
        List<TbFinanceInfo> dayulist=tbFinanceInfoMapper.getdayu(tbFinanceInfo.getReasonTime());
        //遍历dayulist 如果有相同reason_time 就基于update_time 升序asc
        if(dayulist.size()>0){
            double tempbalance=Double.parseDouble(tbFinanceInfo.getBalance());
            for(int i=0;i<dayulist.size();i++){
                TbFinanceInfo dadet=new TbFinanceInfo();
                dadet.setId(dayulist.get(i).getId());
                if(dayulist.get(i).getType()==1){
                    tempbalance=tempbalance-Double.parseDouble(dayulist.get(i).getSum());
                }else {
                    tempbalance=tempbalance+Double.parseDouble(dayulist.get(i).getSum());
                }
                dadet.setBalance(tempbalance+"");
                tbFinanceInfoService.updateById(dadet);
            }
        }
        return true;
    }

    @GetMapping("deletefinanceinfo/{id}")
    @ApiOperation("删除收支")
    public boolean deletefinanceinfo(@PathVariable Integer id){

        //考虑到个内存在多个 先获取update时间
        TbFinanceInfo nowt =tbFinanceInfoService.getById(id);
        Date update=nowt.getUpdateTime();//update可作为重要因素
        //先改掉它自己 再该后面的数据 使顺序不变

        QueryWrapper<TbFinanceInfo> houmian=new QueryWrapper<>();
        houmian.gt("update_time",update);
        houmian.last("order by update_time asc");

        List<TbFinanceInfo> houmians=tbFinanceInfoService.list(houmian);//后面的数据

        //拿到前面的数据
        QueryWrapper<TbFinanceInfo> qianmian=new QueryWrapper<>();
        qianmian.lt("update_time",update);
        qianmian.last("order by update_time desc");
        List<TbFinanceInfo> qianmians=tbFinanceInfoService.list(qianmian);//前面的数据

        boolean a=tbFinanceInfoService.removeById(id);
        double tembalance=0.0;
        if(qianmians.size()>0){
            tembalance=Double.parseDouble(qianmians.get(0).getBalance());
        }
        if(houmians.size()>0){
            for(int i=0;i<houmians.size();i++){
                if(houmians.get(i).getType()==1){//支出
                    tembalance=tembalance-Double.parseDouble(houmians.get(i).getSum());
                }else {
                    tembalance=tembalance+Double.parseDouble(houmians.get(i).getSum());
                }
                houmians.get(i).setBalance(tembalance+"");
                boolean d=tbFinanceInfoService.removeById(houmians.get(i).getId());
                boolean aa=tbFinanceInfoService.save(houmians.get(i));
            }
        }
        return true;
    }

    //无条件分页查询个数
    @GetMapping("getsumbynothing")
    @ApiOperation("无条件分页查询个数")
    public Integer getsumbynothing(){
        return tbFinanceInfoService.count();
    }
    //带条件的分页查询
    @PostMapping("queryinfo")
    @ApiOperation("带条件的分页查询")
    public List<TbFinanceInfo> queryinfo(@RequestBody Financequeryvo financequeryvo){
        financequeryvo.setCurrent((financequeryvo.getCurrent()-1)*financequeryvo.getLimit());
        List<TbFinanceInfo> tbFinanceInfoList=tbFinanceInfoMapper.getinfopages(financequeryvo);
        return tbFinanceInfoList;
    }
    //有条件获取个数
    @PostMapping("queryinfonum")
    @ApiOperation("带条件的分页查询")
    public Integer queryinfonum(@RequestBody Financequeryvo financequeryvo){
        Integer a=tbFinanceInfoMapper.queryinfonum(financequeryvo);
        return a;
    }
    @GetMapping("getlishi")
    @ApiOperation("获取历史数据（报销时间：剩余金额）")
    public List<LishiVo> getlishi(){
        List<LishiVo> list=tbFinanceInfoMapper.getlishi();
        //获取倒排表
        List<LishiVo> daopai=new ArrayList<>();
        List<LishiVo> data=new ArrayList<>();
        SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd");
        String tem="";
        for(int i=0;i<list.size();i++){
            if(list.get(i).getBaoxiaotime().toString().equals(tem)){
                continue;
            }
            tem=list.get(i).getBaoxiaotime().toString();
            daopai.add(list.get(i));
        }
        for(int i=0;i<daopai.size();i++){
            data.add(daopai.get(daopai.size()-1-i));
        }
        return data;
    }




}
